package com.twu.biblioteca;

import java.awt.*;
import java.io.PrintStream;
import java.util.ArrayList;

/**
 * Created by echester on 22/07/2014.
 */
public class Library {
    private ArrayList<Book> books;
    private PrintStream output;

    public Library(PrintStream output) {
        this.books = createBooks();
        this.output = output;
    }

    private ArrayList<Book> createBooks() {
        books = new ArrayList<Book>();
        books.add(new Book("A Game of Thrones", "George RR Martin", 1996));
        books.add(new Book("Butterfly Lion", "Michael Morpurgo", 1996));
        books.add(new Book("UX Design", "Smashing Mag", 2013));

        return books;
    }

    protected ArrayList<Book> getAllBooks() {
        return books;
    }

    protected void checkOut(Book book) {
        book.rent();
    }

    protected void checkIn(Book book) {
        book.returnBook();
    }

    protected ArrayList<Book> getAvailableBooks() {
        ArrayList<Book> available = new ArrayList<Book>();
        for(Book book:books) {
            if (book.isAvailable())
                available.add(book);
        }
        if (available.isEmpty()) throw new NullPointerException("There are no books available!");
        return available;
    }

    protected ArrayList<Book> getUnavailableBooks() {
        ArrayList<Book> unavailable = new ArrayList<Book>();

        for(Book book:books) {
            if(!book.isAvailable())
                unavailable.add(book);
        }
        if (unavailable.isEmpty()) throw new NullPointerException("No books seem to be on loan at the moment!");
        return unavailable;
    }

    protected void printBooksList(ArrayList<Book> books) {
        for(Book book:books) {
            output.printf("%-20.20s %-20.20s%n", book.getTitle(), book.getAuthor());
        }
    }

    protected void printCompleteBookInformation(ArrayList<Book> books) {
        for(Book book: books) {
            output.printf("%-20.20s %-20.20s %-20.20s %-20.20s%n",
                    "ID: " + books.indexOf(book), book.getTitle(), book.getAuthor(), "[" + book.getYearPublished() + "]");
        }
    }
}
